// 押金规则 - Hotel
import { get } from 'lodash';
import { DataTypes, UUIDV4 } from 'sequelize';
import { MySqlModel, getSequelize } from '../db';

const RULE_TYPES = {
  FLAT: 'FLAT', // 一笔固定金额
  NIGHT_FLAT: 'NIGHT_FLAT', // 固定金额*Nights
  PECENT: 'PECENT', // 总费用*Percent
  FIRST_NIGHT_PECENT: 'FIRST_NIGHT_PECENT', // 首晚房价*Percent
  NIGHTS: 'NIGHTS', //前N晚房费作为押金
}

class DepositRule extends MySqlModel {

}

DepositRule.init({
  id: {
    type: DataTypes.UUID, unique: 'id', allowNull: false, defaultValue: UUIDV4, validate: { isUUID: 4 }, primaryKey: true, comment: '主键'
  },
  hotel_id: {
    type: DataTypes.UUID, unique: 'hotel_id_code', allowNull: false, validate: { isUUID: 4 }, comment: '主体'
  },
  code: {
    type: DataTypes.STRING(50), unique: 'hotel_id_code', allowNull: false, comment: '代码'
  },
  name: {
    type: DataTypes.STRING(200), allowNull: false, comment: '名称'
  },
  rule_type: {
    type: DataTypes.STRING(20), allowNull: false, validate: { isIn: { args: [Object.keys(RULE_TYPES)], msg: '无效的规则类型' } }, comment: '规则类型'
  },
  amount: {
    type: DataTypes.DECIMAL(10, 2), allowNull: false, comment: '规则值'
  },
  disabled: {
    type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false, comment: '禁用'
  },
  sequence: {
    type: DataTypes.INTEGER, allowNull: true, defaultValue: null, validate: { min: 0, max: 999999 }, comment: '排序'
  },
  created_id: {
    type: DataTypes.UUID, allowNull: false, validate: { isUUID: 4 }, comment: '创建用户'
  },
  updated_id: {
    type: DataTypes.UUID, allowNull: false, validate: { isUUID: 4 }, comment: '更新用户'
  },
  created_at: {
    type: DataTypes.DATE, allowNull: false, comment: '创建时间'
  },
  updated_at: {
    type: DataTypes.DATE, allowNull: false, comment: '更新时间'
  },
  version: {
    type: DataTypes.INTEGER, allowNull: false, defaultValue: 0, comment: '版本控制'
  }
}, {
  sequelize: getSequelize(),
  tableName: 'deposit_rules',
  comment: '押金规则'
});

DepositRule.beforeDestroy(async (instance, options) => {
  // const { transaction } = options;
  // const room = await getSequelize().models.Room
  //   .findOne({
  //     where: {
  //       room_type_id: instance.id
  //     },
  //     transaction
  //   });
  // if (room) {
  //   throw new Error(`Used By Room ${room.code}`);
  // }
});

// RoomType.associate = (models) => {
//   RoomType.hasMany(models.Room, {
//     sourceKey: 'id',
//     foreignKey: 'room_type_id',
//     as: 'rooms',
//     constraints: false
//   });
// };

export default DepositRule;
